package com.eastcom.collection.script

import com.eastcom.collection.config.FtpTaskConfig
import com.eastcom.collection.provider.SpringContextProvider;

import java.sql.PreparedStatement
import java.sql.SQLException
import java.sql.Timestamp
import java.util.concurrent.ConcurrentLinkedQueue

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.dao.DataAccessException
import org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallback
import org.springframework.jdbc.support.lob.LobCreator
import org.springframework.jdbc.support.lob.OracleLobHandler
import org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import com.eastcom.collection.provider.*
import com.eastcom.collection.config.FtpTaskConfig;
import com.eastcom.collection.tools.db.DbEngine
import com.eastcom.collection.tools.file.JaxbUtil;

class SimpleTaskStoreDirector {
	private static Log logger = LogFactory.getLog(SimpleTaskStoreDirector.class)
	private String taskType = "FTP"
	private String sql = "insert into NHM_PM_UNIT_COLLECT_TASK(TASKID,TASKTYPE,TASKINFO,TIMESTAMP) values(?,?,?,?)"
	public boolean initJob(String jobId){
		
	}

	public boolean doJob(String jobId){
		ConcurrentLinkedQueue ftpTaskReciveQueue = SpringContextProvider.getBean("ftpTaskReciveQueue")
		ConcurrentLinkedQueue ftpTaskWorkQueue = SpringContextProvider.getBean("ftpTaskWorkQueue")
		if(ftpTaskReciveQueue.isEmpty()){
			return true
		}
		final OracleLobHandler lobHandler = new OracleLobHandler()
		CommonsDbcpNativeJdbcExtractor extractor = new CommonsDbcpNativeJdbcExtractor();
		lobHandler.setNativeJdbcExtractor(extractor);
		FtpTaskConfig ftpTaskCf = ftpTaskReciveQueue.poll()
		if(ftpTaskCf != null){
			ftpTaskWorkQueue.add(ftpTaskCf)
			String taskString = JaxbUtil.convertToXmlString(ftpTaskCf)
			String taskId = UUID.randomUUID().toString()
			ftpTaskCf.taskId = taskId
			try {
				DbEngine dbEngine = SpringContextProvider.getBean("dbEngine")
				dbEngine.getJdbcUtil().setDataSource(DynamicBeanDomianProvider.getBean(PropertyPlaceholderConfigurerProvider.getContextProperty("TASK_DATABASE")))
				dbEngine.getJdbcUtil().execute(sql, new AbstractLobCreatingPreparedStatementCallback(lobHandler) {
							protected void setValues(PreparedStatement pstmt, LobCreator lobCreator)
							throws SQLException, DataAccessException {
								Timestamp date = new Timestamp(new java.util.Date().getTime())
								pstmt.setString(1, taskId)
								pstmt.setString(2, taskType)
								lobCreator.setClobAsString(pstmt,3,taskString)
								pstmt.setTimestamp(4,new Timestamp(new Date().getTime()))
							}
						})
				logger.debug("新增一条Ftp任务ID="+taskId)
			} catch (Exception e) {
				logger.error(this, e);
			}
		}
	}

}
